# Some helpers methods for wrapping XML operations (XPath, XSLT, ...)

module XML
  def self.read_xpath(xml, xpath)
    val = REXML::XPath.first(REXML::Document.new(xml), xpath)
    
    case val.class.to_s
    when "NilClass"
      return nil
    when "REXML::Text"
      return val.value
    when "REXML::Element"
      return val.text
    when "REXML::Attribute"
      return val.value
    when "Float"
      return val
    when "Fixnum"
      return val
    else
      raise "Unknown Type #{val.class.to_s}"
    end
  end
  
  def self.write_xpath(xml, xpath, value)
    doc = REXML::Document.new(xml)
    node = REXML::XPath.first(doc, xpath)
    
    case node.class.to_s
    when "REXML::Text"
      node.value = value
    when "REXML::Element"
      node.text = value
    when "REXML::Attribute"
      #overwrite attribute
      node.element.add_attribute(node.name, value)
    else
      raise "Unknown Type #{node.class.to_s}"
    end
    
    return doc.to_s
  end
  
  #TODO Implement. XSLT lib can only work on file system, so apply_xslt method
  # should get xslt as pathname or must create files on his own.
  def self.apply_xslt(xml, xslt)
    
  end
end